from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse

from weixin.account.login_state import decode_state


class check_state_middleware(MiddlewareMixin):
    def process_request(self, request):

        print('验证登录态')

        if request.GET.get('code'):
            return None

        try:
            state = request.META.get("HTTP_COOKIE")
            if state is None:
                print('登录态验证失败')
                data = {
                    'result': False,
                    'message': '请求头中无登录态',
                    'code': 200,
                    'data': {
                    }
                }
                return JsonResponse(data)

            if state == '':
                data = {
                    'result': False,
                    'message': '无效登录态',
                    'code': 200,
                    'data': {
                    }
                }
                return JsonResponse(data)

            result, data = decode_state(state)

        except Exception as e:
            data = {
                'result': False,
                'message': e,
                'code': 500,
                'data': {
                }
            }
            return JsonResponse(data)

        if result:
            setattr(request, 'openid', data[0])
            setattr(request, 'session_key', data[1])
            return None
        else:
            data = {
                'result': False,
                'message': '登录过期',
                'code': 401,  # 用户未认证
                'data': {
                }
            }
            return JsonResponse(data)

















